<template>
  <div class="effciency-band-timeshare">
    <!-- 左布局 -->
    <el-card class="content__left">
      <!-- 下拉列表 -->
      <realtimemonito-menu :data="menus" v-model:menu-id="menuId" v-model:open-id="openId" @menu-click="commEvent.menuClick" />
    </el-card>
    <!-- 右布局 -->
    <div class="content__right">
      <!-- 搜索 -->
      <el-card>
        <el-row :gutter="20" align="middle">
          <el-col :span="6">
            <div class="right-search">
              <div class="search__label">时间：</div>
              <div class="search__value">
                <el-date-picker
                  v-model="searchValue.dataTime"
                  type="date"
                  placeholder="请选择"
                  style="width: 100%"
                  :clearable="false"
                />
              </div>
            </div>
          </el-col>
          <el-col :span="18">
            <el-row justify="end">
              <el-button type="primary" icon="Search" @click="commEvent.getStats">搜索</el-button>
              <el-button icon="Refresh" @click="commEvent.onReset">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-card>
      <!-- 图表 -->
      <el-row :gutter="10" class="mt10">
        <el-col :md="12" :lg="14" :xl="16">
          <el-card>
            <div class="card__title">尖峰平谷配置-峰平谷电量图</div>
            <div v-if="bandElectric.length" class="right-charts mt20">
              <div class="chart-legend">
                <div v-for="item in legendItem" :key="item.color" class="legend__item">
                  <div :style="{ backgroundColor: item.color }" class="legend__item--status"></div>
                  <div class="legend__text">{{ item.name }}</div>
                </div>
              </div>
              <e-charts :option="bandElectricOption" />
            </div>
            <div v-else class="right-charts mt20">
              <el-empty />
            </div>
          </el-card>
        </el-col>
        <el-col :md="12" :lg="10" :xl="8">
          <el-card>
            <div class="card__title">尖峰平谷配置-峰平谷占比图</div>
            <div class="right-charts mt20">
              <e-charts :option="bandRatioOption" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue"
import RealtimemonitoMenu, { MenuType } from "./components/RealtimemonitoMenu.vue"
import ECharts from "@/components/ECharts/index.vue"
import { ECOption } from "@/components/ECharts/config"
import { bandElectricChart, bandRatioChart, legendItem, ratioItem } from "./enum"
import dayjs from "dayjs"
import { organTree } from "@/api/modules/system"
import { SystemSpace as SystemApi } from "@/api/interface/system"
import { peakPlatValleyDleStat, peakPlatValleyRatioStat } from "@/api/modules/efficiency"
import { SystemSpace } from "@/api/interface/efficiency"
// 参数
const openId = ref<number[]>([])
const menuId = ref<number>(-1)
const menus = ref<MenuType[]>([]) // 菜单树结构
// 搜索项
const searchValue = ref({
  dataTime: dayjs().format("YYYY-MM-DD")
})
// 菜单项
const menuValue = ref({
  factoryId: undefined as undefined | number,
  lineId: undefined as undefined | number
})
// 电量图
const bandElectric = ref<SystemSpace.PeakPlatValleyDleStat[]>([])
const bandElectricOption = computed<ECOption>(() => {
  let _series: any = {}
  if (bandElectricChart?.series && Array.isArray(bandElectricChart.series)) {
    _series = bandElectricChart?.series[0]
  }
  return {
    ...bandElectricChart,
    yAxis: { ...bandElectricChart.yAxis, name: `耗电量(${bandElectric.value.length ? bandElectric.value[0].unit : ""})` },
    xAxis: { ...bandElectricChart.xAxis, data: bandElectric.value.map(item => item.dataTime) },
    series: [
      {
        ..._series,
        data: bandElectric.value.map(item => {
          if (item.type == 2) {
            return { itemStyle: { color: "#f9ed69" }, value: item.value }
          } else if (item.type === 3) {
            return { itemStyle: { color: "#afdd22" }, value: item.value }
          }
          return item.value
        })
      }
    ]
  }
})
// 占比图
const bandRatio = ref<any[]>(ratioItem)
const bandRatioOption = computed<ECOption>(() => {
  let _series: any = {}
  if (bandRatioChart?.series && Array.isArray(bandRatioChart.series)) {
    _series = bandRatioChart?.series[0]
  }
  const _sum: number = bandRatio.value.map(item => item.value).reduce((prev: number, next: number) => prev + next, 0)
  return {
    ...bandRatioChart,
    series: [
      {
        ..._series,
        label: {
          ..._series.label,
          formatter: (item: any) => {
            const { name, value } = item
            const _value = _sum === 0 ? 0 : (value / _sum) * 100
            return `${name}${_value.toFixed(2)}%`
          }
        },
        data: bandRatio.value.map(item => ({ name: item.name, value: item.value }))
      }
    ]
  }
})
// 事件
const commEvent = {
  // 获取菜单信息
  getMenus: async () => {
    const { data } = await organTree()
    menus.value = commEvent.formatMenu(data)
    if (data && data.length > 0) {
      const _id: number = data[0].id
      menuId.value = _id
      openId.value = [_id]
    }
    commEvent.getStats()
  },
  // 格式化菜单树
  formatMenu: (data: SystemApi.OrganTree[], pids?: number[]): any[] => {
    if (!data || data.length <= 0) return []
    return data.map(item => {
      let pidArr: number[] = []
      if (pids) {
        pidArr = [...pids, item.pid || 0]
      }
      return {
        id: item.id,
        text: item.organName,
        level: item.level,
        pid: item.pid,
        pidArr,
        children: commEvent.formatMenu(item.childrenTree || [], pidArr)
      }
    })
  },
  // 菜单点击
  menuClick: (item: any) => {
    if (item.level === 1) {
      menuValue.value.factoryId = item.id
      menuValue.value.lineId = undefined
    } else if (item.level === 2) {
      menuValue.value.factoryId = item.pid
      menuValue.value.lineId = item.id
    } else {
      menuValue.value.factoryId = undefined
      menuValue.value.lineId = undefined
    }
    commEvent.getStats()
  },
  // 重置
  onReset: () => {
    searchValue.value.dataTime = dayjs().format("YYYY-MM-DD")
  },
  // 获取统计信息
  getStats: async () => {
    const params: SystemSpace.PeakPlatValleyTotalQuery = {
      ...menuValue.value,
      timeType: 4,
      dataTime: dayjs(searchValue.value.dataTime).format("YYYYMMDD")
    }
    const { data } = await peakPlatValleyDleStat(params)
    bandElectric.value = data.map(item => ({
      ...item,
      dataTime: item.dataTime.substring(item.dataTime.length - 2) + "时"
    }))
    const { data: ratioData } = await peakPlatValleyRatioStat({ ...params, timeType: 3 })
    const _ratioData: any = ratioData
    const _data: any[] = JSON.parse(JSON.stringify(ratioItem))
    _data.forEach(item => {
      item.value = _ratioData[item.key] || 0
      item.unit = _ratioData.unit
    })
    bandRatio.value = _data
  }
}
onMounted(() => {
  commEvent.getMenus()
})
</script>

<style lang="scss" scoped>
.effciency-band-timeshare {
  display: flex;
  width: 100%;
  height: calc(100vh - 100px);
  .card__title {
    position: relative;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    width: 100%;
    padding-left: 8px;
    font-size: 16px;
    font-weight: bold;
    &::before {
      position: absolute;
      left: 0;
      width: 3px;
      height: 75%;
      content: "";
      background-color: #1d4a9d;
      border-radius: 16px;
    }
  }
  .content__left {
    width: 200px;
    :deep(.el-card__body) {
      padding: 0;
    }
    height: 100%;
    overflow-y: auto;
    padding-right: 4px; /* 为滚动条留空间 */
    scroll-behavior: smooth;
    /* 滚动条宽度 */
    &::-webkit-scrollbar {
      width: 3px;
    }
  }
  .content__right {
    box-sizing: border-box;
    flex: 1;
    min-width: 0;
    padding: 0 10px;
    overflow-y: auto;
    .right-search {
      display: flex;
      align-items: center;
      width: 100%;
      .search__label {
        flex-shrink: 0;
        font-size: 13px;
      }
      .search__value {
        flex: 1;
      }
    }
    .right-charts {
      position: relative;
      width: 100%;
      height: 300px;
      .chart-legend {
        position: absolute;
        display: flex;
        gap: 10px;
        justify-content: center;
        width: 100%;
        .legend__item {
          display: flex;
          gap: 5px;
          align-items: center;
          .legend__item--status {
            width: 20px;
            height: 13px;
            border-radius: 3px;
          }
          .legend__text {
            font-size: 13px;
          }
        }
      }
    }
  }
}
</style>
